package com.taojin.shoppinginterest.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.taojin.shoppinginterest.R;
import com.taojin.shoppinginterest.activity.SpecialDetailActivity;
import com.taojin.shoppinginterest.adapter.End_Activity_Adapter;
import com.taojin.shoppinginterest.adapter.Score_Activity_Adapter;
import com.taojin.shoppinginterest.bean.AppSoon;
import com.taojin.shoppinginterest.bean.App_welfare;
import com.taojin.shoppinginterest.bean.End_Activity;
import com.taojin.shoppinginterest.bean.Score_Activity;
import com.taojin.shoppinginterest.constants.ApiConfig;
import com.taojin.shoppinginterest.pop.PopHelper_welfare;

import java.util.ArrayList;
import java.util.List;

public class WelfareFragment extends Fragment implements AdapterView.OnItemClickListener{
    @ViewInject(R.id.pulltorefresh_welfare)
    private PullToRefreshListView pullToRefreshListView;
    @ViewInject(R.id.btn_sort_welfarefragment)
    private Button btn_sort;
    private HttpUtils httpUtils;

    private List<End_Activity> end_activities;
    private List<Score_Activity> score_activities;

    private End_Activity_Adapter end_activity_adapter;
    private Score_Activity_Adapter scoreAdapter;
    boolean flag =false;
    PopupWindow popupWindow;
    private static int sort = 1;
    public WelfareFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.welfarefragment, container, false);
        ViewUtils.inject(this, view);
        httpUtils = new HttpUtils();
        initSoon();
        initData_Score();
        loadData_Socre();
        loadData_End();
        return view;
    }

   /* public void init() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View layout = inflater.inflate(R.layout.pop_welfarefragment, null);
        popupWindow = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        Button btn_dismiss = (Button) layout.findViewById(R.id.btn_dismiss);
        btn_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openMenu();
            }
        });
        btn_sort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openMenu();
            }
        });
        pullToRefreshListView.setOnItemClickListener(this);

    }

    public void openMenu() {
        if (!flag) {
            popupWindow.setAnimationStyle(R.style.PopupAnimation);
            popupWindow.showAtLocation(btn_sort, Gravity.NO_GRAVITY, 0, 0);
            popupWindow.setFocusable(true);
            popupWindow.update();
            flag = true;
        } else {
            popupWindow.dismiss();
            popupWindow.setFocusable(false);
            flag = false;
        }
    }*/
    public void initSoon() {
        btn_sort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopHelper_welfare.getInstance().init(getActivity(), btn_sort, new PopHelper_welfare.CallBack() {
                    @Override
                    public void getPosition(int position) {
                        if (position == 2) {
                            end_activities.clear();
                            score_activities = new ArrayList<Score_Activity>();
                            scoreAdapter = new Score_Activity_Adapter(getActivity(), score_activities);
                            pullToRefreshListView.setAdapter(scoreAdapter);
                            loadData_Socre_soon();
                        } else {
                            initData_Score();
                            loadData_Socre();
                            loadData_End();
                        }
                    }

                });
            }
        });
    }

    /*正在进行的活动的 初始化*/
    public void initData_Score() {
        score_activities = new ArrayList<Score_Activity>();
        scoreAdapter = new Score_Activity_Adapter(getActivity(), score_activities);
        pullToRefreshListView.setAdapter(scoreAdapter);
        pullToRefreshListView.setOnItemClickListener(this);
        pullToRefreshListView.getRefreshableView().addFooterView(footView());
    }

    /*结束的活动 初始化*/
    private void initData_End() {
        end_activities = new ArrayList<End_Activity>();
        end_activity_adapter = new End_Activity_Adapter(getActivity(), end_activities);
        pullToRefreshListView.setAdapter(end_activity_adapter);
        pullToRefreshListView.getRefreshableView().addHeaderView(headView());
    }

    /*头部视图*/
    public View headView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.footview_welfarefragment, null);
        ListView listView = (ListView) view.findViewById(R.id.footview_listview_welfarefragment);
        //   setListViewHeightBasedOnChildren(listView);
        score_activities = new ArrayList<Score_Activity>();
        scoreAdapter = new Score_Activity_Adapter(getActivity(), score_activities);
        listView.setAdapter(scoreAdapter);
        return view;
    }

    public View footView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.footview_welfarefragment, null);
        ListView listView = (ListView) view.findViewById(R.id.footview_listview_welfarefragment);
        end_activities = new ArrayList<End_Activity>();
        end_activity_adapter = new End_Activity_Adapter(getActivity(), end_activities);
        listView.setAdapter(end_activity_adapter);
        return view;
    }

    /*POST参数请求*/
    public RequestParams getRequestParams(int sort) {
        RequestParams requestParams = new RequestParams();
        requestParams.addBodyParameter("app", "score");
        requestParams.addBodyParameter("act", "lists");
        requestParams.addBodyParameter("ver", "1.1");
        requestParams.addBodyParameter("sort", String.valueOf(sort));
        requestParams.addBodyParameter("lat", "31.270763");
        requestParams.addBodyParameter("lon", "121.518044");
        requestParams.addBodyParameter("pt", "2");
        return requestParams;
    }

    /*结束的活动    数据加载*/
    private void loadData_End() {
        httpUtils.send(HttpRequest.HttpMethod.POST, ApiConfig.URL, getRequestParams(1), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String data = responseInfo.result;
                App_welfare app = JSONObject.parseObject(data, App_welfare.class);
                if (app != null) {
                    end_activities.addAll(app.getData().getEnd_activity());
                    end_activity_adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getActivity(), "数据加载失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    /*正在开始的活动  数据加载*/
    private void loadData_Socre() {
        httpUtils.send(HttpRequest.HttpMethod.POST, ApiConfig.URL, getRequestParams(1), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String data = responseInfo.result;
                App_welfare app = JSONObject.parseObject(data, App_welfare.class);
                if (app != null) {
                    score_activities.addAll(app.getData().getScore_activity());
                    scoreAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getActivity(), "数据加载失败", Toast.LENGTH_LONG).show();
            }
        });
    }
    /*即将结束的活动 数据加载*/
    private void loadData_Socre_soon() {
        httpUtils.send(HttpRequest.HttpMethod.POST,  ApiConfig.URL, getRequestParams(2), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String data = responseInfo.result;
                AppSoon app = JSONObject.parseObject(data, AppSoon.class);
                if (app != null) {
                    score_activities.addAll(app.getData().getScore_activity());
                    scoreAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getActivity(), "数据加载失败", Toast.LENGTH_LONG).show();
            }
        });
    }


    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String welfareUrlId=score_activities.get(position).getId();
        String welfareUrl=ApiConfig.getWelfareUrl(welfareUrlId);
        Intent intent=new Intent(getActivity(), SpecialDetailActivity.class);
        Bundle bundle=new Bundle();
        bundle.putString("URL",welfareUrl);
        intent.putExtras(bundle);
        startActivity(intent);

    }
}
